<template>
  <view class="container flex" style="height: 100vh">
    <!-- 表单区域 -->
    <view class="form-container flex-1 overflow-y-auto">
      <view class="form-item">
        <text class="form-label">采购单号</text>
        <text class="form-value">{{ formData.parentCode }}</text>
      </view>
      <view class="form-item">
        <text class="form-label">单据类型</text>
        <text class="form-value">{{ '采购单' }}</text>
      </view>
      <view class="materials-section">
        <text class="form-label">物料名称</text>
        <text class="form-value">{{ formData.productName }}</text>
      </view>
      <view class="materials-section">
        <text class="form-label">供应商</text>
        <text class="form-value">{{ formData.companyName }}</text>
      </view>
      <view class="form-item">
        <text class="form-label">送检ID</text>
        <view class="scan-wrapper">
          <input
            class="form-input scan-input"
            type="text"
            placeholder="请扫描送检ID"
            v-model="formData.inspectionId"
            disabled
          />

          <scanCode @success="getScanCode"></scanCode>
        </view>
      </view>
      <!-- <button
        class="scan-btn"
        @click="
          getScanCode('S2503260000002;PRO0000064;莴笋;10.57;kg;PUR20250326000000001;布吉农批')
        "
      >
        扫码
      </button> -->
      <view class="form-item">
        <text class="form-label">检验类型</text>
        <wd-picker
          @confirm="getSampleNameList"
          :columns="inspectionTypes"
          v-model="formData.qualityType"
        ></wd-picker>
      </view>
      <view class="form-item">
        <text class="form-label">样品种类</text>

        <picker
          @change="handleTypeChange"
          :value="formData.sampleName"
          :range="sampleNameList"
          range-key="sampleName"
          class="picker"
        >
          <view class="picker-value">
            {{ sampleNameList[formData.sampleName]?.sampleName || '请选择检验类型' }}
          </view>
        </picker>
      </view>
      <view class="form-item">
        <text class="form-label">到货数量</text>
        <text class="form-value">{{ formData.purchaseQty }}{{ formatUnit(formData.unit) }}</text>
      </view>
      <view class="form-item">
        <text class="form-label">送检数量</text>
        <input
          class="form-input"
          type="number"
          placeholder="请输入送检数量"
          v-model="formData.inspectQty"
        />
        <text class="form-value">{{ formatUnit(formData.unit) }}</text>
      </view>
      <view class="form-item">
        <text class="form-label">送检时间</text>

        <wd-datetime-picker
          type="date"
          v-model="purchaseDate"
          @confirm="handleDateChange"
          :default-value="defaultValue"
        />
      </view>
    </view>
    <!-- 底部提交按钮 -->
    <view class="submit-container">
      <wd-button :round="false" block class="submit-btn" @click="handleSubmit">提交</wd-button>
    </view>
  </view>
</template>
<script lang="ts" setup>
import GRreportApi, { QualityInspectionReport } from '@/api/GRreport'
import { ScanPatternType } from '@/api/scanCode'
import { reactive } from 'vue'
import { useMessage, useToast } from 'wot-design-uni'
import { formatUnit } from '@/utils/unit'

const toast = useToast()
const message = useMessage()
const formData = reactive<QualityInspectionReport & { inspectionId: string }>({
  parentCode: '',
  actualQuantity: 0,
  category: '1',
  companyCode: '',
  companyName: '',
  inspectQty: 0,
  itemCodeList: [],
  orderType: 1,
  productCode: '',
  productName: '',
  purchaseDate: '',
  qualityType: 1,
  // qualifiedQuantity: 0,
  purchaseQty: 0,
  // qualifiedRate: 100,
  remark: '',
  type: 0,
  unit: '',
  inspectionId: '',
  sampleName: '',
})
const inspectionTypes = ref([
  { label: '果蔬', value: 1 },
  { label: '肉类', value: 2 },
])

//样品种类
const sampleNameList = ref([])

//获取样品种类
const getSampleNameList = ({ value }) => {
  console.log(value)
  formData.sampleName = ''
  formData.qualityType = value
  GRreportApi.getLastReportBySampleName({
    sampleName: formData.sampleName,
    type: formData.qualityType,
  }).then((res) => {
    sampleNameList.value = res.data
  })
}

const getScanCode = (code: string) => {
  console.log(code)

  if (ScanPatternType.BASKET_CODE_TIMESTAMP.test(code)) {
    if (code.split(';')[1] !== formData.productCode) {
      toast.error('请扫描正确的产品标签码')
    } else {
      formData.inspectionId = code.split(';')[0]
      formData.inspectQty = Number(code.split(';')[3])
    }
  } else {
    return toast.error('请扫描正确的条码')
  }
}
const handleSubmit = () => {
  // 提交表单逻辑
  console.log('提交表单数据：', formData)
  if (formData.inspectQty <= 0) {
    return toast.error('请输入送检数量')
  }
  if (formData.qualityType != 1 && formData.qualityType != 2) {
    return toast.error('请选择检验类型')
  }
  if (formData.sampleName == '') {
    return toast.error('该检验类型暂无检验项')
  }
  GRreportApi.saveReport(formData)
    .then((res) => {
      uni.showToast({
        title: '保存成功',
        icon: 'none',
      })
    })
    .then(() => {
      //清空
      formData.itemCodeList = []
      formData.inspectionId = ''
      formData.qualityType = 1
      formData.inspectQty = 0
      formData.sampleName = ''
    })
}

// 根据检验类型获取上次检验项
const getLastInspectionItems = (type: string) => {
  console.log(type, 'type', sampleNameList.value[type]?.sampleName)

  // 根据检验类型获取上次检验项的逻辑
  GRreportApi.getLastReportBySampleName({
    sampleName: sampleNameList.value[type]?.sampleName,
    type: formData.qualityType,
  }).then((res) => {
    console.log(res, 'data')
    res.data.map((item) => {
      item.qcItemCode = item.code
    })
    formData.itemCodeList = res.data
  })
}

function formatDate(date: Date): string {
  const year = date.getFullYear()

  const month = String(date.getMonth() + 1).padStart(2, '0')

  const day = String(date.getDate()).padStart(2, '0')

  return `${year}-${month}-${day}`
}
// 处理日期选择
const defaultValue = ref<number>(Date.now())
const purchaseDate = ref(Date.now())
const handleDateChange = ({ value }) => {
  console.log(value)
  formData.purchaseDate = new Date(value).toLocaleDateString().replaceAll('/', '-')
}
// 处理类型选择

const handleTypeChange = (e: any) => {
  formData.sampleName = e.detail.value

  getLastInspectionItems(e.detail.value)
}
onLoad((options) => {
  // 设置默认日期
  formData.purchaseDate = formatDate(new Date())
  console.log(options, 'options')
  console.log(JSON.parse(options.purchaseOrder), JSON.parse(options.purchaseOrderInfo))

  const purchaseOrder = JSON.parse(options.purchaseOrder)
  formData.parentCode = purchaseOrder.parentCode
  formData.category = purchaseOrder.category
  formData.productCode = purchaseOrder.productCode
  formData.productName = purchaseOrder.productName
  formData.purchaseQty = purchaseOrder.qty
  formData.unit = purchaseOrder.unit
  const purchaseOrderInfo = JSON.parse(options.purchaseOrderInfo)
  formData.companyCode = purchaseOrderInfo.companyCode
  formData.companyName = purchaseOrderInfo.companyName

  getSampleNameList({ value: 1 })
})
</script>
<style lang="scss">
page {
  height: 100%;
  background-color: #f7f8fa;
}

.container {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 124rpx);
}

.form-container {
  flex: 1;
  padding: 40rpx 30rpx;
  background-color: #ffffff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
}

.form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);

  &:last-child {
    border-bottom: none;
  }
}

.form-label {
  position: relative;
  flex-shrink: 0;
  width: 160rpx;
  font-weight: 500;
  color: #333333;
}

.form-value {
  padding-left: 20rpx;
  font-weight: 400;
  color: #333333;
}

.form-input {
  height: 76rpx;
  padding: 0 28rpx;
  margin: 0 28rpx;
  color: #333333;
  background: #f8f9fc;
  border: 1px solid #ebedf5;
  border-radius: 12rpx;
  transition: all 0.3s ease;

  &::placeholder {
    color: #b2b2b2;
  }

  &:focus {
    background: #ffffff;
    border-color: #2979ff;
    box-shadow: 0 0 0 2px rgba(41, 121, 255, 0.1);
  }
}

.scan-wrapper {
  display: flex;
  flex: 1;
  gap: 24rpx;
  align-items: center;
}

.scan-btn {
  width: 160rpx;
  height: 76rpx;
  padding: 0;
  font-size: 28rpx;
  line-height: 76rpx;
  color: #ffffff;
  background: linear-gradient(135deg, #4c8dff 0%, #2979ff 100%);
  border-radius: 12rpx;
  box-shadow: 0 6rpx 12rpx rgba(41, 121, 255, 0.2);
  transition: all 0.3s ease;

  &:active {
    box-shadow: 0 2rpx 4rpx rgba(41, 121, 255, 0.2);
    transform: scale(0.98);
  }
}

.picker-value {
  height: 76rpx;
  padding: 0 28rpx;
  line-height: 76rpx;
  color: #333333;
  border-radius: 12rpx;
  transition: all 0.3s ease;
}

.materials-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 28rpx 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);

  .form-value {
    font-weight: 500;
    color: #2979ff;
  }
}

.submit-container {
  // position: fixed;
  // right: 0;
  // bottom: 0;
  // left: 0;
  display: flex;
  height: 100rpx;
  padding: 12rpx 28rpx;
  background-color: #fff;
  box-shadow: 0 -4rpx 24rpx rgba(0, 0, 0, 0.06);

  .submit-btn {
    width: 100%;

    margin: 0;
    font-size: 32rpx;
    font-weight: 600;
    color: #ffffff;
    background: linear-gradient(135deg, #4c8dff 0%, #2979ff 100%);
    border-radius: 16rpx;
    box-shadow: 0 8rpx 16rpx rgba(41, 121, 255, 0.2);
    transition: all 0.3s ease;

    &:active {
      box-shadow: 0 4rpx 8rpx rgba(41, 121, 255, 0.2);
      transform: scale(0.98);
    }
  }
}

.form-unit {
  margin-left: 12rpx;
  font-size: 28rpx;
  color: #666666;
}
</style>
